package com.gismore.demo.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import org.apache.commons.lang3.ClassUtils;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RET<T> implements Serializable{
	private static final long serialVersionUID = 6621506314768915730L;
	private Integer status;//业务编码
	private String message;
	private T data;
	
	public RET(T data) {
		this.status = 200;
		this.data = data;
	}
	public RET(@NotNull Integer code, String message) {
		this.status = code;
		this.message = message;
	}
	public RET(Exception e) {
		this(500, e);
	}

	public RET(Integer code, Throwable e) {
		this.status = 500;
		String packageName = ClassUtils.getPackageName(this.getClass());
		String packagePrefix = Arrays.stream(packageName.split("\\.")).limit(2).collect(Collectors.joining("."));
		Optional<StackTraceElement> stackTraceElementOptional = Arrays.stream(e.getStackTrace()).filter(r->r.toString().contains(packagePrefix)).findFirst();
		String exceptionDetail;
		if(stackTraceElementOptional.isPresent()){
			exceptionDetail = stackTraceElementOptional.get().toString();
		}else{
			exceptionDetail = e.getStackTrace()[0].toString();
		}
		this.message = "'"+e.getMessage() + "' => " + exceptionDetail;
	}


	@Override
	public String toString(){
		JSONObject ret = new JSONObject(true);
		ret.put("status",this.getStatus());
		return JSON.toJSONString(this, SerializerFeature.NotWriteDefaultValue,SerializerFeature.SortField);
	}

}
